package com.uni.controllers;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import com.uni.db.GenericService;
import com.uni.domain.Course;
import com.uni.domain.Discipline;
import com.uni.utils.CreatorFromId;

@Controller
@RequestMapping("/courseEdit.htm")
@SessionAttributes(types = Course.class)
public class CourseEdit {

    @Autowired
	@Qualifier("courseService")
	private GenericService<Course> courseService;

    @Autowired
	@Qualifier("disciplineService")
	private GenericService<Discipline> disciplineService;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Discipline.class, new CreatorFromId<Discipline>(disciplineService));
    }

    @RequestMapping(method = RequestMethod.GET)
	public String setupForm(@RequestParam(value="id", required=false) Long id, ModelMap model) {
		Course course;
		if (id == null || id < 1){
			course = new Course();
		} else {
			course = courseService.get(id);
		}
        model.addAttribute("course", course);

        return "courseEdit";
	}

    @ModelAttribute("disciplines")
    public Collection<Discipline> getDisciplines() {
        return disciplineService.listAll();
    }


    @RequestMapping(method = RequestMethod.POST)
	public String processSubmit(@ModelAttribute Course course, BindingResult result, SessionStatus status) {
		if (result.hasErrors()) {
			return "courseEdit";
		} else {
			courseService.save(course);
			status.setComplete();
			return "redirect:/course/" + course.getId();
		}
	}
}

